package com.zhdl.common.ytools;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 时间处理类
 */
public class DateTimeHelper {
    /**
     * 计算两个yyyy-MM-dd HH:mm:ss时间，相差的秒数
     *
     * <p>
     * {@code
     * String startTime = "2020-01-01 01:00:00";
     * String endTime = "2020-01-01 02:00:00";
     * long sec = DateTimeHelper.calcDurationSec(startTime, endTime);
     * }
     */
    public static long calcDurationSec(String startTime, String endTime) {
        // 定义日期时间格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 将字符串格式的时间转换为 LocalDateTime 类型
        LocalDateTime startDateTime = LocalDateTime.parse(startTime, formatter);
        LocalDateTime endDateTime = LocalDateTime.parse(endTime, formatter);

        // 计算两个时间之间的差值，并将差值转换为秒数
        Duration duration = Duration.between(startDateTime, endDateTime);
        return duration.toSeconds();
    }

    /**
     * 将秒转换为时间描述字符，3600，显示为1天
     *
     * @param seconds
     * @return
     */
    public static String secondToTimeString(long seconds) {
        long day = seconds / (60 * 60 * 24);
        long hour = (seconds % (60 * 60 * 24)) / 3600;
        long minute = (seconds % (60 * 60)) / 60;
        long second = seconds % 60;  // 余数就是剩余的秒

        StringBuilder out = new StringBuilder();
        if (day > 0) out.append(String.format("%d天", day));
        if (hour > 0) out.append(String.format("%d小时", hour));
        if (minute > 0) out.append(String.format("%d分钟", minute));
        if (second > 0) out.append(String.format("%d秒", second));

        return out.toString();
    }

    /**
     * 将毫秒转换为时间描述字符，3600 * 1000，显示为1天
     *
     * @param totalMs
     * @return
     */
    public static String msToTimeString(long totalMs) {
        long day = totalMs / (60 * 60 * 24 * 1000);
        long hour = (totalMs - (day * 24 * 60 * 60 * 1000)) / (60 * 60 * 1000);
        long minute = (totalMs - (day * 24 * 60 * 60 * 1000) - (hour * 60 * 60 * 1000)) / (60 * 1000);
        long second = (totalMs - (day * 24 * 60 * 60 * 1000) - (hour * 60 * 60 * 1000) - (minute * 60 * 1000)) / 1000;
        long millisecond = totalMs - (day * 24 * 60 * 60 * 1000) - (hour * 60 * 60 * 1000) - (minute * 60 * 1000) - (second * 1000);

        StringBuilder out = new StringBuilder();
        if (day > 0) out.append(String.format("%d天", day));
        if (hour > 0) out.append(String.format("%d小时", hour));
        if (minute > 0) out.append(String.format("%d分钟", minute));
        if (second > 0) out.append(String.format("%d秒", second));
        if (millisecond > 0) out.append(String.format("%d毫秒", millisecond));

        return out.toString();
    }

}
